//查找字符串中是否包含单词
function contains(str, word) {
  return str.indexOf(word) > -1;
}

/**
 * 上传表单内容
 * */
//上传表单图片并显示在页面上
var imgsrc = "";
iptfile.addEventListener("change", function (e) {
  e.preventDefault();
  var formData = new FormData();
  formData.append("file", iptfile.files[0]);
  // formData.append("text", document.getElementById("textS").value);
  axios.post(apirUrl + "/api/uploadimg", formData).then(function (res) {
    console.log(res.data);
    show_img.src = apirUrl + res.data.src;
    text_center.style.display = "block";
    noneimg.style.display = "none";
    imgsrc = res.data.src;
    // console.log(imgsrc);
  });
});
/**
 * 上传内容
 * */
var submitnews = document.getElementById("submitnews");
submitnews.addEventListener("click", function () {
  console.log(imgsrc);
  axios
    .post(apirUrl + "/api/insertNews", {
      title: document.getElementById("title").value,
      text: document.getElementById("text").value,
      keyword: document.getElementById("keyword").value,
      imgsrc: imgsrc,
    })
    .then(function (res) {
      console.log(res.data);
      if (res.data.status == 1) {
        if (contains(res.data.message, "imgsrc")) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML = "上传的图片不能为空";
          toast.show();
        } else if (contains(res.data.message, "5 characters long")) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML =
            "新闻标题<strong> Title </strong>不能少于<strong> 5 </strong>个字符!";
          toast.show();
        } else if (contains(res.data.message, "40 characters long")) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML =
            "新闻标题<strong> Title </strong>不能多于<strong> 40 </strong>个字符!";
          toast.show();
        } else if (contains(res.data.message, "text")) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML =
            "新闻内容<strong> Text </strong>不能少于50个字符!";
          toast.show();
        } else if (
          contains(res.data.message, '"title" is not allowed to be empty')
        ) {
          me_uto.innerHTML = "上传失败";
          toast_body.innerHTML = "新闻标题<strong> Title </strong>不能为空!";
          toast.show();
        }
      } else if (res.data.status == 0) {
        me_uto.innerHTML = "上传成功";
        toast_body.innerHTML = "您已成功上传一则新闻！";
        toast.show();
        iptfile.value = "";
        text_center.style.display = "none";
        noneimg.style.display = "block";
        document.getElementById("title").value = "";
        document.getElementById("text").value = "";
        document.getElementById("keyword").value = "";
      }
    });
});
